package com.jwthhealth_pub.old.subscribe;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.util.Log;

import com.baidu.location.BDLocation;
import com.jwthhealth_pub.R;
import com.jwthhealth_pub.common.LogUtil;
import com.jwthhealth_pub.old.api.ApiHelper;
import com.jwthhealth_pub.old.api.model.CommonRespone;
import com.jwthhealth_pub.old.common.location.BaiduLocation;
import com.jwthhealth_pub.old.sign.model.LoginModel;
import com.jwthhealth_pub.old.signutil.model.db.UserInfoDao;
import com.jwthhealth_pub.old.subscribe.model.SubscribeIndex;
import com.jwthhealth_pub.old.subscribe.model.SubscribeList;
import com.jwthhealth_pub.old.subscribe.model.SubscribeTimeList;

import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.jwthhealth_pub.common.LogUtil.makeLogTag;

/**
 * 预约 presenter
 * Created by Administrator on 2017/7/12.
 */

class SubscribePresenter implements SubscribeContect.presenter {

    private static String TAG = makeLogTag(SubscribePresenter.class);

    private SubscribeContect.view mView;
    private SubscribeActivity mActivity;

    private int mGetLocationCount = 0;

    SubscribePresenter(SubscribeContect.view mView) {
        this.mView = mView;
        this.mActivity = (SubscribeActivity) mView;
    }

    @Override
    public void location() {
        if (Build.VERSION.SDK_INT >= 23 && ContextCompat.checkSelfPermission(mActivity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            mActivity.requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 11);
        } else {
            mActivity.showLoadProgresbar();
            new BaiduLocation(mActivity, new BaiduLocation.BDLocacionReceiver() {
                @Override
                public void onReceiverLocation(BDLocation location) {
                    LogUtil.i("百度定位:" + "纬度:" + location.getLatitude() + " " + "经度:" + location.getLongitude() + " " + "反地理编码:" + location.getAddrStr(), TAG);

                    final String city = location.getCity();
                    final String district = location.getDistrict();

                    if (city == null || district == null) {
                        if (mGetLocationCount != 2) {
                            mGetLocationCount++;
                            location();
                        } else {
                            mView.refreshCurAdd("定位失败, 请手动选择");
                            return;
                        }

                    }

                    mActivity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (city == null && district == null)
                                mView.refreshCurAdd("定位失败, 请手动选择");
                            else
                                mView.refreshCurAdd(city + " " + district);
                        }
                    });

                    getShopsinfo(String.valueOf(location.getLatitude()), String.valueOf(location.getLongitude()));
                }
            });
        }
    }

    @Override
    public void getCloseShopInfo(String provinceName, String cityName, String zoneName) {
        Call<SubscribeIndex> shopInfo = ApiHelper.getShopInfo(provinceName, cityName, zoneName);
        shopInfo.enqueue(new Callback<SubscribeIndex>() {
            @Override
            public void onResponse(@NonNull Call<SubscribeIndex> call, @NonNull Response<SubscribeIndex> response) {
                SubscribeIndex body = response.body();
                if (body == null) return;
                if (body.getCode().equals("0")) {
                    final List<SubscribeIndex.DataBean> data = body.getData();
                    mActivity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Log.d(TAG, "省市区接口刷新界面");
                            mView.refreshUi(data);
                        }
                    });
                } else {
                    Log.e(TAG, "code isnt 0");
                    if (body.getMsg() != null)
                        mActivity.toast(body.getMsg());
                }
            }

            @Override
            public void onFailure(@NonNull Call<SubscribeIndex> call, @NonNull Throwable t) {
                mActivity.errorToast();
                Log.e(TAG, t.toString());
            }
        });
    }

    @Override
    public void getShopsinfo(String latitude, String longitude) {
        // 获取到最近的门店信息,刷新整个页面
        Call<SubscribeIndex> shopInfo = ApiHelper.getShopInfo(latitude, longitude);
        shopInfo.enqueue(new Callback<SubscribeIndex>() {
            @Override
            public void onResponse(@NonNull Call<SubscribeIndex> call, @NonNull Response<SubscribeIndex> response) {
                SubscribeIndex body = response.body();
                if (body == null || body.getCode() == null) return;
                if (body.getCode().equals("0")) {
                    final List<SubscribeIndex.DataBean> data = body.getData();
                    mActivity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mView.refreshUi(data);
                        }
                    });
                } else {
                    Log.e(TAG, "code isnt 0");
                }
            }

            @Override
            public void onFailure(@NonNull Call<SubscribeIndex> call, @NonNull Throwable t) {
                Log.e(TAG, t.toString());
                mActivity.missLoadProgressbar();
                mActivity.toast(mActivity.getString(R.string.common_net_error));
            }
        });

    }

    @Override
    public void shopInfo(String lat, String lon) {
        final Call<SubscribeIndex> _call = ApiHelper.getShopInfo(lat, lon);
        Observable<List<SubscribeIndex.DataBean>> observable = Observable.create(new ObservableOnSubscribe<List<SubscribeIndex.DataBean>>() {
            @Override
            public void subscribe(ObservableEmitter<List<SubscribeIndex.DataBean>> e) throws Exception {
                SubscribeIndex body = _call.execute().body();

                if (body == null) {
                    e.onError(new Exception("reponse is null"));
                    return;
                }

                if (body.getCode().equals("1")) {
                    e.onError(new Exception(body.getMsg()));
                    return;
                }

                e.onNext(body.getData());
            }
        });

        Observer<List<SubscribeIndex.DataBean>> observer = new Observer<List<SubscribeIndex.DataBean>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(List<SubscribeIndex.DataBean> data) {
                mView.refreshUi(data);
            }

            @Override
            public void onError(Throwable e) {
                LogUtil.toast(mActivity.getString(R.string.common_net_error));
            }

            @Override
            public void onComplete() {

            }
        };

        observable.subscribe(observer);

    }

    @Override
    public void getTimeList(String pid, String sid, String date) {
        if (mActivity.isProgressBarShow) return;
        mActivity.showLoadProgresbar();
        Call<SubscribeTimeList> _call = ApiHelper.getSubscribeTimeList(pid, sid, date);
        _call.enqueue(new Callback<SubscribeTimeList>() {
            @Override
            public void onResponse(@NonNull Call<SubscribeTimeList> call, @NonNull Response<SubscribeTimeList> response) {
                final SubscribeTimeList body = response.body();
                if (body == null || body.getCode() == null) return;
                if (body.getCode().equals("0")) {
                    mActivity.missLoadProgressbar();
                    mActivity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mActivity.showTimeList(body.getData());
                        }
                    });
                } else {
                    if (body.getMsg() == null) return;
                    mActivity.toast(body.getMsg());
                }
            }

            @Override
            public void onFailure(@NonNull Call<SubscribeTimeList> call, @NonNull Throwable t) {
                mActivity.missLoadProgressbar();
                String packageName = mActivity.getPackageName();
                Log.d(TAG, packageName);
                LogUtil.e(t.toString(), packageName);
            }
        });

    }

    @Override
    public void addAdd(String provinceName, String cityName, String zoneName) {
        //添加地址
        LoginModel.DataBean userinfoModel = UserInfoDao.getInstance().queryUserinfoModel();
        if (userinfoModel != null) {
            Call<CommonRespone> call = ApiHelper.addSubscribeAddress(userinfoModel.getId(), provinceName, cityName, zoneName, userinfoModel.getAndroidtoken());
            call.enqueue(new Callback<CommonRespone>() {
                @Override
                public void onResponse(@NonNull Call<CommonRespone> call, @NonNull Response<CommonRespone> response) {
                    CommonRespone body = response.body();
                    if (body == null || body.getMsg() == null) return;
                    LogUtil.i(body.getMsg(), TAG);
                }

                @Override
                public void onFailure(@NonNull Call<CommonRespone> call, @NonNull Throwable t) {
                    LogUtil.e(t.toString(), TAG);
                }
            });
        } else {
            Log.d(TAG, "userinfo is null");
        }
    }

    @Override
    public void getCacheData() {
        SubscribeList.DataBean cacheData = mActivity.getIntent().getParcelableExtra("subscribe_data");
        if (cacheData != null)
            mActivity.refreshCache(cacheData);
        else
            LogUtil.i("no cache subscribe data", TAG);
    }
}
